package mutipackage;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;


import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;


public class MClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MClient mainClient = new MClient();
		mainClient.work() ;

	}

	private void work() {

		IoConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new MutiProtocalCodecFactory(Charset
						.forName("UTF-8"))));
		connector.setHandler(new MClientHandler());
		connector.getSessionConfig().setReadBufferSize(100);
		connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		ConnectFuture connFuture = connector.connect(new InetSocketAddress(ServerConfiguration.PORT));
		connFuture.addListener(new IoFutureListener<ConnectFuture>() {
			public void operationComplete(ConnectFuture future) {
				try {
					if (future.isConnected()) {
						IoSession session = future.getSession();
						sendData(session);
					} else {
						System.out.println("连接不存在 ");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			private void sendData(IoSession session) {
				StringBuffer bu = new StringBuffer() ;
				for (int i = 0; i <20; i++) {
					bu.append("测试文本"+i) ;
				}
				bu.append("\n end");
				session.write(bu.toString()) ;
			}
		});
		
	}

}

class MClientHandler extends IoHandlerAdapter {
	@Override
	public void sessionOpened(IoSession session) {
		session.getConfig().setIdleTime(IdleStatus.READER_IDLE, 60);
	}

	@Override
	public void sessionClosed(IoSession session) {
		System.err.println("Total " + session.getReadBytes() + " byte(s)");
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) {
		if (status == IdleStatus.READER_IDLE) {
			session.close(true);
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message) {
		String pack = (String) message;
		System.out.println("rec:" + pack);
	}
}
